package de.beuth.hochschule.ats.activitys;

import java.sql.SQLException;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.j256.ormlite.android.apptools.OrmLiteBaseListActivity;

import de.beuth.hochschule.ats.R;
import de.beuth.hochschule.ats.entitys.DatabaseHelper;
import de.beuth.hochschule.ats.entitys.Lecture;

public class ShowLectures extends OrmLiteBaseListActivity<DatabaseHelper>
		implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lectures);
		findViewById(R.id.save_button).setOnClickListener(this);
		setTitle(R.string.lectures);
	}

	@Override
	protected void onResume() {
		super.onResume();
		List<Lecture> lectures;
		try {
			lectures = getHelper().getLectureDao().queryForAll();
			setListAdapter(new ArrayAdapter<Lecture>(this, R.layout.row,
					lectures));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Lecture lecture = (Lecture) l.getItemAtPosition(position);
		Intent i = new Intent(this, ShowLecture.class);
		i.setAction(Intent.ACTION_EDIT);
		i.putExtra("lecture_id", lecture.getId());
		startActivity(i);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu from XML resource
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.lectures_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.d("foo", item.getItemId() + "");
		switch (item.getItemId()) {
		case R.id.add:
			Intent intent = new Intent(this, EditLecture.class);
			intent.setAction(Intent.ACTION_INSERT);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onClick(View v) {
		Intent intent = new Intent(this, EditLecture.class);
		intent.setAction(Intent.ACTION_INSERT);
		startActivity(intent);
	}

}
